package com.ruoyi.activity.service.impl;

import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.ruoyi.activity.domain.InfoBean;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.crops.domain.Crops;
import com.ruoyi.crops.mapper.CropsMapper;
import com.ruoyi.inputs.mapper.InputsMapper;
import com.ruoyi.land.domain.ArgoLand;
import com.ruoyi.land.mapper.ArgoLandMapper;
import com.ruoyi.product.mapper.ArgoProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.activity.mapper.ArgoActivityMapper;
import com.ruoyi.activity.domain.ArgoActivity;
import com.ruoyi.activity.service.IArgoActivityService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 农事活动信息Service业务层处理
 * 
 * @author qhr
 * @date 2024-02-27
 */
@Service
public class ArgoActivityServiceImpl implements IArgoActivityService 
{
    @Autowired
    private ArgoActivityMapper argoActivityMapper;

    @Autowired
    private CropsMapper cropsMapper;

    @Autowired
    private ArgoLandMapper landMapper;

    @Autowired
    private InputsMapper inputsMapper;

    @Autowired
    private ArgoProductMapper productMapper;

    @Autowired
    private Crops crops;

    @Autowired
    private InfoBean infoBean;

    /**
     * 查询农事活动信息
     * 
     * @param id 农事活动信息主键
     * @return 农事活动信息
     */
    @Override
    public ArgoActivity selectArgoActivityById(Long id)
    {
        return argoActivityMapper.selectArgoActivityById(id);
    }

    /**
     * 查询农事活动信息列表
     * 
     * @param argoActivity 农事活动信息
     * @return 农事活动信息
     */
    @Override
    public List<ArgoActivity> selectArgoActivityList(ArgoActivity argoActivity)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        System.out.println(loginUser);
        return argoActivityMapper.selectArgoActivityList(argoActivity);
    }

    /**
     * 新增农事活动信息
     * 
     * @param argoActivity 农事活动信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertArgoActivity(ArgoActivity argoActivity)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        argoActivity.setUserId(loginUser.getUserId());
        argoActivity.setCreateTime(DateUtils.getNowDate());

        System.out.println(argoActivity.getActType());
        if (argoActivity.getActType().equals("0")){ //播种活动
            System.out.println("insert(播种活动) -> 新增农作物");
            executeSowActivity(crops,argoActivity);
        } else if (argoActivity.getActType().equals("4")) { //采收活动
            System.out.println("insert(采收活动) -> 农作物->农产品 & 农产品储量+1");
            executePickActivity(crops,argoActivity);
        } else if (argoActivity.getActType().equals("2") || argoActivity.getActType().equals("3")) { // 施肥/农药活动
            System.out.println("insert(施肥/农药) -> 消耗投入品余量");
            if (inputsMapper.selectInputsById(argoActivity.getInputsId()).getStock() >= argoActivity.getInputsNum()) {
                inputsMapper.updateStock(argoActivity.getInputsNum(),argoActivity.getInputsId()); //消耗投入品存量
                executeFertilizerOrChemical(argoActivity);
            } else {
                throw new ArithmeticException("投入品余量不足");
            }
        } else if (argoActivity.getActType().equals("8")) {

        }
        return argoActivityMapper.insertArgoActivity(argoActivity);
    }

    /**
     * 修改农事活动信息
     * 
     * @param argoActivity 农事活动信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateArgoActivity(ArgoActivity argoActivity)
    {
        System.out.println("updateArgoActivity -> "+argoActivity);
        if (argoActivity.getActType().equals("0")){ //播种活动
            System.out.println("insert(播种活动) -> 新增农作物");

        } else if (argoActivity.getActType().equals("4")) { //采收活动
            System.out.println("insert(采收活动) -> 农作物->农产品 & 农产品储量+1");

        } else if (argoActivity.getActType().equals("2") || argoActivity.getActType().equals("3")) { //施肥和喷洒农药活动
            System.out.println("insert(施肥/农药) -> 消耗投入品余量");

        }
        return argoActivityMapper.updateArgoActivity(argoActivity);
    }

    /**
     * 批量删除农事活动信息
     * 
     * @param ids 需要删除的农事活动信息主键
     * @return 结果
     */
    @Override
    public int deleteArgoActivityByIds(Long[] ids)
    {
        return argoActivityMapper.deleteArgoActivityByIds(ids);
    }

    /**
     * 删除农事活动信息信息
     * 
     * @param id 农事活动信息主键
     * @return 结果
     */
    @Override
    public int deleteArgoActivityById(Long id)
    {
        int result = argoActivityMapper.deleteArgoActivityById(id);
        return result;
    }

    /**
     * 播种活动
     *
     */
    private void executeSowActivity (Crops crops, ArgoActivity argoActivity) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        crops.setCropsName(inputsMapper.selectInputsById(argoActivity.getInputsId()).getRemark());
        crops.setCreateTime(DateUtils.getNowDate());
        crops.setCreateBy(loginUser.getUsername());
        crops.setSowPattern(argoActivity.getActDepict());

        ArgoLand existingArgoLand = landMapper.selectArgoLandById(loginUser.getDeptId());
        try {
            if (existingArgoLand != null) {

                existingArgoLand.setCropsId(argoActivity.getCropsId());
                landMapper.updateArgoLand(existingArgoLand);
            } else {
                throw new Exception("未找到匹配的ArgoLand记录");
            }
        } catch (Exception e) {
            ExceptionUtil.getExceptionMessage(e);
        }
        // 空对象检查
        if (crops == null) {
            throw new IllegalArgumentException("Crops object cannot be null");
        }
        cropsMapper.insertCrops(crops);
    }
    /**
     * 采收活动
     *
     */
    private void executePickActivity (Crops crops, ArgoActivity argoActivity) {
        crops.setPickPattern(argoActivity.getActDepict());
        crops.setPickedTime(DateUtils.getNowDate());
        crops.setId(argoActivity.getCropsId());

        LoginUser loginUser = SecurityUtils.getLoginUser();
        ArgoLand existingArgoLand = landMapper.selectArgoLandById(loginUser.getDeptId());
        System.out.println(existingArgoLand);
        try {
            if (existingArgoLand != null) {
                existingArgoLand.setId(loginUser.getDeptId());
                existingArgoLand.setCropsId(null);
                landMapper.updateArgoLand(existingArgoLand);
                Long stock=1L; //增量
                productMapper.updateStock(stock,argoActivity.getProductId()); //农产品储量+#{stock}
//                cropsMapper.deleteCropsById(argoActivity.getCropsId()); //农作物->农产品
                cropsMapper.updateCrops(crops); //更新采摘时间和采摘方式
            } else {
                throw new Exception("未找到匹配的ArgoLand记录");
            }
        } catch (Exception e) {
            ExceptionUtil.getExceptionMessage(e);
        }
    }
    /**
     * 施肥/农药 活动
     *
     */
    private void executeFertilizerOrChemical (ArgoActivity argoActivity) {
        infoBean.setDate(argoActivity.getCreateTime());
        infoBean.setName(inputsMapper.selectInputsById(argoActivity.getInputsId()).getInputsName());
        crops=cropsMapper.selectCropsById(argoActivity.getCropsId());

        if (argoActivity.getActType().equals("2")) {
            infoBean.setNum(argoActivity.getInputsNum().intValue());
            infoBean.setUnit("kg"); //固定单位格式
            List<InfoBean> infoBeanList = JSON.parseArray(crops.getFertilizerInfo(),InfoBean.class); //原jsonString转换为List

            infoBeanList.add(infoBean); //List添加新数据
            crops.setFertilizerInfo(JSON.toJSONString(infoBeanList, JSONWriter.Feature.WriteNullStringAsEmpty)); //新的List转换为jsonString
        } else if (argoActivity.getActType().equals("3")) {
            infoBean.setNum(argoActivity.getInputsNum().intValue());
            infoBean.setUnit("g"); //固定单位格式
            List<InfoBean> infoBeanList = JSON.parseArray(crops.getChemicalInfo(),InfoBean.class); //原jsonString转换为List

            infoBeanList.add(infoBean); //List添加新数据
            crops.setChemicalInfo(JSON.toJSONString(infoBeanList, JSONWriter.Feature.WriteNullStringAsEmpty)); //新的List转换为jsonString
        }
        cropsMapper.updateCrops(crops);
    }
}
